using System;
using System.Threading;
using Microsoft.SPOT;
using NetduinoHappyHour.Behaviour;
using NetduinoHappyHour.Hardware;
using NetduinoHappyHour.Util;

namespace NetduinoHappyHour.Asynchronous
{
    /// <summary>
    /// Class to run objects, without waitung for them to be finished
    /// </summary>
    public class ExecuteAsync : BaseAsyncHandler
    {
        private String _objectName;
        private Object _objectToRun;

        /// <summary>
        /// Default constructor for test environment only
        /// </summary>
        public ExecuteAsync()
        {
        }

        /// <summary>
        /// Runs a specific object without any construction parameters
        /// </summary>
        /// <param name="ObjectName">the object to be executed</param>
        public ExecuteAsync(String ObjectName)
        {
            _objectName = ObjectName;
            _objectToRun = new ObjectFactory().CreateObjectByNameAndParam(_objectName);
        }

        /// <summary>
        /// Runs a specific object without any construction parameters
        /// </summary>
        /// <param name="ObjectName">the object to be executed</param>
        public ExecuteAsync(Object ObjectToRun)
        {
            _objectName = ObjectToRun.ToString();
            _objectToRun = ObjectToRun;
        }

        /// <summary>
        /// Executes the object set by construction
        /// </summary>
        public override void ThreadProc()
        {
            try
            {
                if (_objectToRun is IExecutable)
                {
                    ((IExecutable)_objectToRun).Execute();
                }
            }
            catch (Exception Ex)
            {
                SystemStatus.Instance().AddMessage(_objectName + ";" + Ex.Message + Ex.StackTrace);
            }
        }
    }
}
